package com.ohs.ohsoa.system.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ohs.ohsoa.system.dto.OvertimeLeaveInfoParamDto;
import com.ohs.ohsoa.system.entity.HolidaySetting;
import com.ohs.ohsoa.system.entity.OvertimeLeaveInfo;
import com.ohs.ohsoa.system.entity.OvertimeLeaveStatistics;
import com.ohs.ohsoa.system.entity.Pushlog;
import com.ohs.ohsoa.system.mapper.OvertimeLeaveInfoMapper;
import com.ohs.ohsoa.system.vo.OvertimeLeaveInfoParamVo;
import com.ohs.ohsoa.utils.IsNull;
import com.ohs.ohsoa.utils.bean.requestBean.PageParam;
import com.ohs.ohsoa.utils.exception.BizException;

/**
 * 加班欠勤明细实现接口
 *
 * @author hds
 */
@Service
public class OvertimeLeaveInfoServiceImpl extends ServiceImpl<OvertimeLeaveInfoMapper, OvertimeLeaveInfo>
		implements OvertimeLeaveInfoService {

	@Resource
	private OvertimeLeaveInfoMapper overtimeLeaveInfoMapper;

	@Resource
	private MessageSource messageSource;

	@Resource
	private OvertimeLeaveStatisticService overtimeLeaveStatisticService;

	@Resource
	private HolidaySettingService holidaySettingService;

	@Resource
	private PushlogService pushlogService;

	@Override
	public List<OvertimeLeaveInfoParamVo> overtimeleaveinfoSelectList(PageParam<OvertimeLeaveInfoParamDto> pageParam) {
		// 获取overtimeLeaveInfoParamDtor对象
		OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto = pageParam.getSearchbean();
		// 获取并返回user集合
		List<OvertimeLeaveInfoParamVo> overtimeLeaveInfoParamVos = new ArrayList<>();
		// 1: 自己申请页面
		if ("1".equals(overtimeLeaveInfoParamDto.getFlg())) {
			// 用户id
			overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
					.overtimeleaveinfoSelectListByOneself(overtimeLeaveInfoParamDto);
		} else {
			// 0 超级管理员 1：普通员工
			if ("0".equals(overtimeLeaveInfoParamDto.getSuperflg())) {
				overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
						.overtimeleaveinfoSelectListBySuperFlg(overtimeLeaveInfoParamDto);
			} else {
				// 判断是否是组长
				List<String> result = new ArrayList<>();
				if (overtimeLeaveInfoParamDto.getUserGuid() != null) {
					result = overtimeLeaveInfoMapper.selectcountsubgroupmanage(overtimeLeaveInfoParamDto.getUserGuid());
				}
				// 是否是部长 1：是 0 否
				if ("1".equals(overtimeLeaveInfoParamDto.getLeaderFlg())) {
					if (result != null && result.size() > 0 && !"0".equals(result.get(0))) {
						// 又是部长又是组长
						if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
							overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
									.overtimeleaveinfoSelectListByLeaderFlgAndSelectFlag(overtimeLeaveInfoParamDto);
						}
					} else {
						// 只是部长
						if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {

							overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
									.overtimeleaveinfoSelectListBySelectFlag(overtimeLeaveInfoParamDto);
						}
					}
					// 检索条件管理者 1：部长 2：组长 3：员工
					if (overtimeLeaveInfoParamDto.getManagerFlg().equals("2")) {
						if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
							overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
									.overtimeleaveinfoSelectListBySelectFlagAndManagerFlg(overtimeLeaveInfoParamDto);
						}
					}
				} else {
					// 组长可以看到的人
					if (result != null && result.size() > 0) {
						if (!IsNull.isNull(result.get(0))) {
							if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
								overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
										.overtimeleaveinfoSelectListCanSeeBySelectFlag(overtimeLeaveInfoParamDto);
							}
						}
					}
				}
			}
		}

		for (OvertimeLeaveInfoParamVo overtimeLeaveInfoParamVo : overtimeLeaveInfoParamVos) {
			if (overtimeLeaveInfoParamVo.getOliFlag().equals("1")) {
				if (overtimeLeaveInfoParamVo.getOvertimeType().equals("1")) {
					overtimeLeaveInfoParamVo.setLsName("普通加班");
					overtimeLeaveInfoParamVo.setLsName("假日加班（周六日）");
					overtimeLeaveInfoParamVo.setLsName("法定节假日加班");
				}
			}
		}

		return overtimeLeaveInfoParamVos;
	}

//    @Override
//    public List<OvertimeLeaveInfoParamVo> overtimeleaveinfoSelectList(
//            PageParam<OvertimeLeaveInfoParamDto> pageParam) {
//        // 获取overtimeLeaveInfoParamDtor对象
//        OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto = pageParam.getSearchbean();
//        // 分页
//        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
//        // 获取并返回user集合
//        List<OvertimeLeaveInfoParamVo> overtimeLeaveInfoParamVos = new ArrayList<>();
//        // 1: 自己申请页面
//        if ("1".equals(overtimeLeaveInfoParamDto.getFlg())) {
//            // 用户id
//            overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                    .overtimeleaveinfoSelectListByOneself(overtimeLeaveInfoParamDto);
//        } else {
//            // 0 超级管理员 1：普通员工
//            if ("0".equals(overtimeLeaveInfoParamDto.getSuperflg())) {
//                overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                        .overtimeleaveinfoSelectListBySuperFlg(overtimeLeaveInfoParamDto);
//            } else {
//                // 判断是否是组长
//                List<String> result = new ArrayList<>();
//                if (overtimeLeaveInfoParamDto.getUserGuid() != null) {
//                    result = overtimeLeaveInfoMapper.selectcountsubgroupmanage("b23b7e63b17147caae46e96939795466");
//                }
//                // 是否是部长 1：是 0 否
//                if ("1".equals(overtimeLeaveInfoParamDto.getLeaderFlg())) {
//                    if (result != null && result.size() > 0 && !IsNull.isNull(result.get(0))) {
//                        // 又是部长又是组长
//                        if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
//                            overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                                    .overtimeleaveinfoSelectListByLeaderFlgAndSelectFlag(overtimeLeaveInfoParamDto);
//                        }
//                    } else {
//                        // 只是部长
//                        if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
//                            overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                                    .overtimeleaveinfoSelectListBySelectFlag(overtimeLeaveInfoParamDto);
//                        }
//                    }
//                    // 检索条件管理者 1：部长 2：组长 3：员工
//                    if (overtimeLeaveInfoParamDto.getManagerFlg().equals("2")) {
//                        if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
//                            overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                                    .overtimeleaveinfoSelectListBySelectFlagAndManagerFlg(overtimeLeaveInfoParamDto);
//                        }
//                    }
//                } else {
//                    // 组长可以看到的人
//                    if (result != null && result.size() > 0) {
//                        if (!IsNull.isNull(result.get(0))) {
//                            if (!"1".equals(overtimeLeaveInfoParamDto.getSelectFlag())) {
//                                overtimeLeaveInfoParamVos = overtimeLeaveInfoMapper
//                                        .overtimeleaveinfoSelectListCanSeeBySelectFlag(overtimeLeaveInfoParamDto);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        for (OvertimeLeaveInfoParamVo overtimeLeaveInfoParamVo : overtimeLeaveInfoParamVos) {
//            if (overtimeLeaveInfoParamVo.getOliFlag().equals("1")) {
//                if (overtimeLeaveInfoParamVo.getOvertimeType().equals("1")) {
//                    overtimeLeaveInfoParamVo.setLsName("普通加班");
//                    overtimeLeaveInfoParamVo.setLsName("假日加班（周六日）");
//                    overtimeLeaveInfoParamVo.setLsName("法定节假日加班");
//                }
//            }
//        }
//        return overtimeLeaveInfoParamVos;
//    }

	@Override
	public List<OvertimeLeaveInfoParamVo> overtimeleaveinfoSelect(OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto) {
		return overtimeLeaveInfoMapper.overtimeleaveinfoSelect(overtimeLeaveInfoParamDto);
	}

	@Override
	public Boolean overtimeleaveinfoInsert(OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto) {
		boolean result = selectcounttime(overtimeLeaveInfoParamDto.getBeginTime(),
				overtimeLeaveInfoParamDto.getEndTime(), overtimeLeaveInfoParamDto.getUserGuid(),
				overtimeLeaveInfoParamDto.getOliGuid());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		// 将字符串形式的时间转化为Date类型的时间
		try {
			Date a = sdf.parse(overtimeLeaveInfoParamDto.getEndTime());
			Date b = sdf.parse(overtimeLeaveInfoParamDto.getBeginTime());
			if (a.getTime() - b.getTime() <= 0
					&& !"00:00".equals(overtimeLeaveInfoParamDto.getEndTime().substring(11))) {
				// 数据出错
				throw new BizException("E00015", messageSource.getMessage("E00015", null, null));
			} else if (result) {
				OvertimeLeaveInfo overtimeLeaveInfo = new OvertimeLeaveInfo();
				BeanUtils.copyProperties(overtimeLeaveInfoParamDto, overtimeLeaveInfo);
				if (overtimeLeaveInfoParamDto.getOliFlag().equals("1")) {
					// TODO 根据实际日期判断加班类型
					String overtimeType = this.checkDayOfHoliday(overtimeLeaveInfoParamDto.getBeginTime());
					overtimeLeaveInfoParamDto.setOvertimeType(overtimeType);
				}
				overtimeLeaveInfo.setVerifiedState("0");
				overtimeLeaveInfo.setCreateTime(LocalDateTime.now().toString());
				overtimeLeaveInfo.setUpdateTime("1900-01-01");
				overtimeLeaveInfo.setDeleteFlag("1");
				overtimeLeaveInfo.setDeleteTime("1900-01-01");
				return this.save(overtimeLeaveInfo);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		throw new BizException("E0003", messageSource.getMessage("E0003", new String[] { "申請時間", "申請時間" }, null));
	}

	/**
	 * 1：普通加班 2：假日加班（周六日） 3：法定节假日加班
	 *
	 * @param beginTime 开始时间
	 */
	private String checkDayOfHoliday(String beginTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = sdf.parse(beginTime);
			QueryWrapper<HolidaySetting> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("hs_time", date);
			if (holidaySettingService.count(queryWrapper) > 0) {
				return "3";
			} else {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(date);
				if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
						|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
					return "2";
				} else {
					return "1";
				}
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@Transactional
	public Boolean overtimeleaveinfoDelete(OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto) {
		for (String oliGuid : overtimeLeaveInfoParamDto.getOliGuids()) {
			String result = overtimeLeaveInfoMapper.selectverifiedstatebymore(oliGuid);
			if ("0".equals(result)) {
				UpdateWrapper<OvertimeLeaveInfo> updateWrapper = new UpdateWrapper<>();
				updateWrapper.eq("oli_guid", oliGuid).set("delete_flag", "0").set("delete_time",
						LocalDateTime.now().toString());
				this.update(updateWrapper);
//                overtimeLeaveInfoMapper.overtimeleaveinfoDelete(oliGuid);
			} else {
				throw new BizException("E0004", messageSource.getMessage("E0004", null, null));
			}
		}
		return null;
	}

	@Override
	public Boolean overtimeleaveinfoUpdate(OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto) {
		boolean result = selectcounttime(overtimeLeaveInfoParamDto.getBeginTime(),
				overtimeLeaveInfoParamDto.getEndTime(), overtimeLeaveInfoParamDto.getUserGuid(),
				overtimeLeaveInfoParamDto.getOliGuid());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date a = sdf.parse(overtimeLeaveInfoParamDto.getEndTime());
			Date b = sdf.parse(overtimeLeaveInfoParamDto.getBeginTime());

			if (a.getTime() - b.getTime() <= 0
					&& !"00:00".equals(overtimeLeaveInfoParamDto.getEndTime().substring(11))) {
				// 数据出错
				throw new BizException("E00015", messageSource.getMessage("E00015", null, null));
			} else if (result) {
				String count = overtimeLeaveInfoMapper.selectverifiedstate(overtimeLeaveInfoParamDto.getOliGuid());
				if ("1".equals(count)) {
					OvertimeLeaveInfo overtimeLeaveInfo = new OvertimeLeaveInfo();
					BeanUtils.copyProperties(overtimeLeaveInfoParamDto, overtimeLeaveInfo);
					overtimeLeaveInfo.setUpdateTime(LocalDateTime.now().toString());
					return this.updateById(overtimeLeaveInfo);
				} else {
					// 数据出错
					throw new BizException("E0004", messageSource.getMessage("E0004", null, null));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean overtimeleaveinfoVerified(OvertimeLeaveInfoParamDto overtimeLeaveInfoParamDto) {
		for (String oliGuid : overtimeLeaveInfoParamDto.getOliGuids()) {
			UpdateWrapper<OvertimeLeaveInfo> updateWrapper = new UpdateWrapper<>();
			updateWrapper.eq("oli_guid", oliGuid).set("verified_state", overtimeLeaveInfoParamDto.getVerifiedState())
					.set("verified_user", overtimeLeaveInfoParamDto.getVerifiedUser())
					.set("verified_time", LocalDateTime.now().toString());
			OvertimeLeaveInfo overtimeLeaveInfo = this.getById(oliGuid);
			QueryWrapper<OvertimeLeaveStatistics> overtimeLeaveStatisticsQueryWrapper = new QueryWrapper<>();
			overtimeLeaveStatisticsQueryWrapper.eq("user_guid", overtimeLeaveInfo.getUserGuid())
					.eq("ols_year", String.valueOf(LocalDateTime.now().getYear()))
					.eq("group_enterprise_guid", overtimeLeaveInfo.getGroupEnterpriseGuid());
			OvertimeLeaveStatistics overtimeLeaveStatistics = overtimeLeaveStatisticService
					.getOne(overtimeLeaveStatisticsQueryWrapper);

			// 审核通过 添加时长到 加班欠勤合计
			if (overtimeLeaveInfoParamDto.getVerifiedState().equals("1")) {
				// overtimeLeaveStatistics表中有此人今年数据
				if (overtimeLeaveStatistics != null) {
					// oliFlag 1：加班 2：请假 0：系统发放 3：系统清算
					if (overtimeLeaveInfo.getOliFlag().equals("1")) {
						overtimeLeaveStatistics
								.setOvertimeLongtime(new BigDecimal(overtimeLeaveStatistics.getOvertimeLongtime())
										.add(new BigDecimal(overtimeLeaveInfo.getTotalTimes())).toString());
					} else if (overtimeLeaveInfo.getOliFlag().equals("2")) {
						overtimeLeaveStatistics
								.setLeaveLongtime(new BigDecimal(overtimeLeaveStatistics.getLeaveLongtime())
										.add(new BigDecimal(overtimeLeaveInfo.getTotalTimes())).toString());
					}
					// TODO 0,3两种情况暂未考虑
					overtimeLeaveStatisticService.updateById(overtimeLeaveStatistics);
				} else {
					OvertimeLeaveStatistics newovertimeLeaveStatistics = new OvertimeLeaveStatistics();
					newovertimeLeaveStatistics.setGroupEnterpriseGuid(overtimeLeaveInfo.getGroupEnterpriseGuid());
					newovertimeLeaveStatistics.setUserGuid(overtimeLeaveInfo.getUserGuid());
					newovertimeLeaveStatistics.setPaidVacationLongtime("0");
					newovertimeLeaveStatistics.setLongVacationLongtime("0");
					newovertimeLeaveStatistics.setYearVacationLongtime("0");
					newovertimeLeaveStatistics.setOlsYear(String.valueOf(LocalDateTime.now().getYear()));
					if (overtimeLeaveInfo.getOliFlag().equals("1")) {
						newovertimeLeaveStatistics.setOvertimeLongtime(overtimeLeaveInfo.getTotalTimes());
						newovertimeLeaveStatistics.setLeaveLongtime("0");
					} else if (overtimeLeaveInfo.getOliFlag().equals("2")) {
						newovertimeLeaveStatistics.setLeaveLongtime(overtimeLeaveInfo.getTotalTimes());
						newovertimeLeaveStatistics.setOvertimeLongtime("0");
					}
					overtimeLeaveStatisticService.save(newovertimeLeaveStatistics);
				}
			}
			this.update(updateWrapper);
			// 新增消息通知
			Pushlog pushlog = new Pushlog();
			pushlog.setPersonnelGuid(overtimeLeaveInfo.getUserGuid());
			pushlog.setPcontent("残業/休暇はもう審査しました。");
			pushlog.setCreateTime(LocalDateTime.now().toString());
			pushlog.setPreadflg("0");
			pushlog.setDeleteFlg("1");
			pushlogService.save(pushlog);
		}
		return true;
	}

	/**
	 * 判断时间是否重复
	 */
	private boolean selectcounttime(String begintime, String endtime, String userid, String oliGuid) {

		boolean result = true;

		try {
			List<OvertimeLeaveInfoParamVo> data = overtimeLeaveInfoMapper.selectcounttime(begintime, endtime, userid,
					oliGuid);
			for (OvertimeLeaveInfoParamVo str : data) {
				// String overtime_type = (String) str[0];
				String oli_flag = str.getOliFlag();
				// 0为福利发放1为加班2为请假
				if ("1".equals(oli_flag) || "2".equals(oli_flag)) {
					result = false;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

}
